//
//  SyncHttpRequest.m
//  baovn
//
//  Created by Nghia Dang on 1/11/13.
//  Copyright (c) 2013. All rights reserved.
//

#import "SyncHttpRequest.h"
#import "ConsumerLock.h"

@implementation SyncHttpRequest

- (id)initWithRequest:(NSURLRequest *)urlRequest callback:(void(^)(NSData *callbackData)) callback
{
    if (self = [super init])
    {
        self.lock = [ConsumerLock new];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [NSURLConnection connectionWithRequest:urlRequest delegate:self];
            while(!self.lock.finished)
            {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        });
        
        [self.lock consume:^(NSData *data) {
            if (callback != nil)
            {
                callback(data);
            }
        }];
    }
    
    return self;
}

+ (void)connectionWithRequest:(NSURLRequest *)urlRequest callback:(void(^)(NSData *data)) callback
{
#ifndef __clang_analyzer__
    SyncHttpRequest *connection;
    connection = [[SyncHttpRequest alloc] initWithRequest:urlRequest callback:callback];
#endif
}

#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    
    if ([httpResponse statusCode] == HTTP_REPONSE_OK)
    {
//        NSDictionary *dic =  httpResponse.allHeaderFields;
        
        if (_data)
        {
            _data = nil;
        }
        
        _data = [[NSMutableData alloc] init];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (_data)
    {
        [_data appendData:data];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self.lock produce:nil];
    [self.lock finish];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.lock produce:_data];
    [self.lock finish];
}

- (void)dealloc
{
    _data = nil;
}
@end
